package com.li.configserve.config.mybatis;

import com.li.toolkit.constant.LogConst;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2022/1/17 21:22
 */
@Component
public class MybatisConfig {

    private static final Logger logger = LoggerFactory.getLogger(MybatisConfig.class);

    @Autowired
    private DataSource dataSource;

    /**
     * @Bean
     */
    public SqlSessionFactory sqlSessionFactory() {
        SqlSession sqlSession = null;
        try {
            // 采用Mybatis的JDBC事务方式
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("menagerie", transactionFactory, dataSource);
            // 创建Configuration对象
            Configuration configuration = new Configuration(environment);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
            sqlSession = sqlSessionFactory.openSession();
            logger.info(LogConst.LOG_SUCCESS_PREFIX + "SqlSessionFactory 获取完成！");
            return sqlSessionFactory;
        } catch (Exception e) {
            logger.error(LogConst.ERROR + e.getMessage());
            return null;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * 创建 MapWrapperFactory 的 Bean 解决 Map 结果中 key 的大小写
     *
     * @return
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "Mybatis Map 结果 Key 大小写配置注册完成！");
        return configuration -> configuration.setObjectWrapperFactory(new MapWrapperFactory());
    }


}
